const {verifyJWT} = require('../../util/jwt')

const jwtValidator = (require = true)=>{
    return async (req,res,next)=>{
        const Authorization = req.headers.authorization
        const token =Authorization ? Authorization.split('Bearer ')[1] : ''
        if(token){
            try{
                const jwtResult = await verifyJWT(token)
                //req内的信息可以传递到下一个req中
                req.userinfo = jwtResult
                next()
                
            }catch{
                res.status(404).json({
                    error:1,
                    msg:'token无效'
                })
            }
            
        }else {
            //如果是需要登录的
            if(require){
                res.status(404).json({
                    error:1,
                    msg:'token值为空'
                })
            }else{
                //不需要登录的信息 直接执行next
                next()
            }
        }
    
      
    }
}

exports.jwtValidator = jwtValidator